/**
 * 
 */
package reco.db.validation;

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.isBlank;
import reco.db.Constraint;

/**
 * Restriccion empleada para asegurarse que un campo de string no quede en blanco.
 */
public final class SizeConstraint extends Constraint<String> {
    private final int maxSize;
    private final int minSize;

    public SizeConstraint(int constraintMinSize, int constraintMaxSize) {
        super("size", "illegalSize");

        if (constraintMaxSize < constraintMinSize) {
            this.minSize = constraintMaxSize;
            this.maxSize = constraintMinSize;
        } else {
            this.minSize = constraintMinSize;
            this.maxSize = constraintMaxSize;
        }

        checkArgument(this.minSize >= 0, "minSize must be positive");
        checkArgument(this.maxSize > 0, "maxSize must be greater than 0");
    }

    @Override
    public boolean validate(String value) {
        if (isBlank(value)) {
            return true;
        }
        return value.length() <= this.maxSize && value.length() >= this.minSize;
    }

    @Override
    public Object[] getErrorArguments() {
        return new Object[] { this.minSize, this.maxSize };
    }
}
